﻿#region

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MediaController.Client.DAL;
using MediaController.Extractor.Properties;
using MediaController.Utils.UI;

#endregion

namespace MediaController.Extractor
{
    public class Unpacker : Form
    {

        public const string DEFAULT_NAME = "Scene Unpacker";
        private readonly ArchiveCollection _archives = new ArchiveCollection();
        private bool _collapsed;
        private bool _processCanceled;
        private CheckBox appendPrefix;
        private CheckBox appendSourceName;
        private NumericUpDown archiveDepth;
        private CheckedListBox archives;
        private Label archivesCount;
        private CheckBox archivesSelectionControl;
        private Button cancelCommnad;
        private IContainer components;
        private ToolStripStatusLabel currentArchive;
        private ToolStripStatusLabel currentFile;
        private ToolStripStatusLabel currentFileBw;
        private ToolStripStatusLabel currentFileExtracted;
        private ToolStripStatusLabel currentFilePercentage;
        private ToolStripStatusLabel currentVolume;
        private ToolStripStatusLabel elapsed;
        private TextBox extraContent;
        private ToolStripStatusLabel fileElapsed;
        private ToolStripProgressBar fileProgress;
        private FolderBrowserDialog folderBrowserDialog1;
        private GroupBox groupBox1;
        private GroupBox groupBox2;
        private GroupBox input;
        private Label label1;
        private Label label2;
        private Label label3;
        private Label label4;
        private Label label6;
        private ToolStripProgressBar overallProgress;
        private Button pauseCommand;
        private Timer processTimer;
        private TextBox sourceFolder;
        private Button sourceFolderBrowse;
        private Button startCommand;
        private StatusStrip statusStrip1;
        private StatusStrip statusStrip2;
        private Button targetBrowse;
        private ComboBox targetFolder;
        private FolderBrowserDialog targetFolderBrowser;
        private ToolTip toolTip1;


        public Unpacker()
        {
            InitializeComponent();
            folderBrowserDialog1.ShowNewFolderButton = true;
            folderBrowserDialog1.Description = "Select the folder containing your archives.";
            targetFolderBrowser.ShowNewFolderButton = true;
            targetFolderBrowser.Description = "Select target folder.";
            new DragDropSupport(this, sourceFolder_Drop);
            new DragDropSupport(targetFolder, targetFolder_Drop);
            _archives.ExtraContent = extraContent.Text = Settings.Default.ExtraContent;
            _archives.ContentChanged += archiveCollection_ContentChanged;
            _archives.ArchiveFound += archiveCollection_ArchiveFound;
            _archives.DestinationChanged += archiveCollection_DestinationChanged;
            _archives.ProcessStarted += archiveCollection_ProcessStarted;
            _archives.ProcessNextArchive += archiveCollection_ProcessNextArchive;
            _archives.ArchiveProcessed += archiveCollection_ArchiveProcessed;
            _archives.ProcessEnded += archiveCollection_ProcessEnded;
            var monitor = new WindowStateMonitor(this);
            monitor.Maximized += form_Maximized;
            monitor.Normalized += form_Normalized;
            if (Settings.Default.Destinations != null)
            {
                var array = new string[Settings.Default.Destinations.Count];
                Settings.Default.Destinations.CopyTo(array, 0);
                targetFolder.Items.AddRange(array);
                if ((targetFolder.Text == string.Empty) && (targetFolder.Items.Count != 0))
                {
                    //targetFolder.SelectedIndex = Settings.Default.Destinations_SelectedIndex;
                }
            }
            appendSourceName.Checked = Settings.Default.Append_SourceName;
            appendPrefix.Checked = Settings.Default.Append_Prefix;
            archiveDepth.Value = Settings.Default.ArchiveDepth;
            sourceFolder.Text = GetDefaultFolder().ToString();
        }

        public ArchiveCollection Archives
        {
            get { return _archives; }
        }

        private void AddArchive(Archive a)
        {
            if (archives.InvokeRequired)
            {
                var method = new AddArchiveCallback(AddArchive);
                archives.Invoke(method, new object[] { a });
            }
            else
            {
                archives.Items.Add(a, true);
            }
        }

        private void archiveCollection_ArchiveFound(object sender, Archive a)
        {
            AddArchive(a);
        }

        private void archiveCollection_ArchiveProcessed(object sender, Archive a)
        {
            if (statusStrip1.InvokeRequired)
            {
                statusStrip1.Invoke(new PerformStepDelegate(PerformStep));
            }
            else
            {
                overallProgress.PerformStep();
            }
        }

        private void archiveCollection_ContentChanged(ArchiveCollection sender)
        {
            string str = (sender.Source == null) ? string.Empty : sender.Source.ToString();
            if (!str.Equals(".") && !str.Equals(sourceFolder.Text))
            {
                sourceFolder.Text = str;
            }
            Text = (sender.Source != null) ? sender.Source.Name : string.Empty;
            archives.Items.Clear();
            Application.DoEvents();
        }

        private void archiveCollection_DestinationChanged(ArchiveCollection sender, DirectoryInfo newDestination)
        {
            string str = (newDestination == null) ? string.Empty : newDestination.ToString();
            if (!str.Equals(".") && !str.Equals(targetFolder.Text))
            {
                targetFolder.Text = newDestination.ToString();
            }
        }

        private void archiveCollection_ProcessEnded(ArchiveCollection sender)
        {
            if (base.InvokeRequired)
            {
                base.Invoke(new ProcessEndedDelegate(archiveCollection_ProcessEnded), new object[] { sender });
            }
            else
            {
                processTimer.Stop();
                processTimer = null;
                UpdateElapsedTime();
                startCommand.Enabled = true;
                pauseCommand.Enabled = false;
                cancelCommnad.Enabled = false;
                input.Enabled = true;
            }
        }

        private void archiveCollection_ProcessNextArchive(object sender, Archive a)
        {
            if (base.InvokeRequired)
            {
                base.Invoke(new ProcessNextArchiveDelegate(archiveCollection_ProcessNextArchive),
                            new[] { sender, a });
            }
            else
            {
                currentArchive.Text = a.ToString();
                fileProgress.Value = 0;
                fileProgress.Visible = true;
                AttachHandlers(a.Unrar);
                int index = archives.Items.IndexOf(a);
                archives.SetSelected(index, true);
            }
        }

        private void archiveCollection_ProcessStarted(ArchiveCollection sender)
        {
            if (base.InvokeRequired)
            {
                base.Invoke(new ProcessStartedDelegate(archiveCollection_ProcessStarted), new object[] { sender });
            }
            else
            {
                overallProgress.Step = 100 / sender.ArchivesCount;
                overallProgress.Value = 0;
                overallProgress.Visible = true;
                _processCanceled = false;
                startCommand.Enabled = false;
                pauseCommand.Enabled = true;
                cancelCommnad.Enabled = true;
                input.Enabled = false;
                processTimer = new Timer(components);
                processTimer.Interval = 100;
                processTimer.Tick += processTimer_Tick;
                processTimer.Start();
            }
        }

        private void archiveInput_TextChanged(object sender, EventArgs e)
        {
            string text = sourceFolder.Text;
            if (text != string.Empty)
            {
                try
                {
                    var info = new DirectoryInfo(text);
                    _archives.Source = info;
                }
                catch
                {
                    _archives.Source = null;
                }
            }
        }

        private void archives_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            int num = archives.CheckedItems.Count;
            num = num + ((e.NewValue == CheckState.Checked) ? 1 : -1);
            archivesCount.Text = string.Concat(new object[] { "", num, "(", archives.Items.Count, ")" });
            if (num == 0)
            {
                archivesSelectionControl.CheckState = CheckState.Unchecked;
            }
            else
            {
                if (num == archives.Items.Count)
                {
                    archivesSelectionControl.CheckState = CheckState.Checked;
                }
                else
                {
                    archivesSelectionControl.CheckState = CheckState.Indeterminate;
                }
            }
            startCommand.Enabled = num > 0;
        }

        private void archivesSelectionControl_Click(object sender, EventArgs e)
        {
            if (archivesSelectionControl.CheckState == CheckState.Indeterminate)
            {
                archivesSelectionControl.CheckState = CheckState.Unchecked;
            }
        }

        private void AttachHandlers(Unrar unrar)
        {
            unrar.NewFile += unrar_NewFile;
            unrar.NewVolume += unrar_NewVolume;
            unrar.ExtractionProgress += unrar_ExtractionProgress;
            unrar.MissingVolume += unrar_MissingVolume;
            unrar.PasswordRequired += unrar_PasswordRequired;
            unrar.OutOfDiskSpace += unrar_OutOfDiskSpace;
        }

        internal bool BrowseSourceFolder()
        {
            var dialog = new FolderBrowserDialog();
            dialog.SelectedPath = GetDefaultFolder().ToString();
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                string selectedPath = dialog.SelectedPath;
                _archives.Source = new DirectoryInfo(selectedPath);
                // Settings.Default.ArchiveSource = selectedPath;
                return true;
            }
            return false;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (targetFolder.Text != string.Empty)
            {
                targetFolderBrowser.SelectedPath = targetFolder.Text;
            }
            if (targetFolderBrowser.ShowDialog(this) == DialogResult.OK)
            {
                if (!targetFolder.Items.Contains(targetFolderBrowser.SelectedPath))
                {
                    targetFolder.Items.Insert(0, targetFolderBrowser.SelectedPath);
                }
                _archives.Destination = new DirectoryInfo(targetFolderBrowser.SelectedPath);
            }
        }

        private void cancelCommnad_Click(object sender, EventArgs e)
        {
            _processCanceled = true;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (_archives != null)
            {
                _archives.AppendArchivePrefix = appendPrefix.Checked;
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (archivesSelectionControl.CheckState != CheckState.Indeterminate)
            {
                base.SuspendLayout();
                bool flag = archivesSelectionControl.Checked;
                for (int i = 0; i < archives.Items.Count; i++)
                {
                    archives.SetItemChecked(i, flag);
                }
                base.ResumeLayout();
            }
        }

        private void ClearArchives()
        {
            if (archives.InvokeRequired)
            {
                var method = new ClearArchivesCallback(ClearArchives);
                archives.Invoke(method, new object[0]);
            }
            else
            {
                archives.Items.Clear();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void extraContent_TextChanged(object sender, EventArgs e)
        {
            _archives.ExtraContent = extraContent.Text;
        }

        private void form_Maximized(object sender, EventArgs e)
        {
            statusStrip1.SizingGrip = false;
        }

        private void form_Normalized(object sender, EventArgs e)
        {
            statusStrip1.SizingGrip = true;
        }

        internal DirectoryInfo GetDefaultFolder()
        {
            string path = (_archives.Source != null) ? _archives.Source.FullName : "";//Settings.Default.ArchiveSource;
            if (path == string.Empty)
            {
                path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            }
            while ((path != string.Empty) && !Directory.Exists(path))
            {
                path = Directory.GetParent(path).ToString();
            }
            return new DirectoryInfo(path);
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.cancelCommnad = new System.Windows.Forms.Button();
            this.pauseCommand = new System.Windows.Forms.Button();
            this.startCommand = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.appendSourceName = new System.Windows.Forms.CheckBox();
            this.targetBrowse = new System.Windows.Forms.Button();
            this.archives = new System.Windows.Forms.CheckedListBox();
            this.sourceFolderBrowse = new System.Windows.Forms.Button();
            this.sourceFolder = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.targetFolderBrowser = new System.Windows.Forms.FolderBrowserDialog();
            this.input = new System.Windows.Forms.GroupBox();
            this.archivesSelectionControl = new System.Windows.Forms.CheckBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.label2 = new System.Windows.Forms.Label();
            this.extraContent = new System.Windows.Forms.TextBox();
            this.archivesCount = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.archiveDepth = new System.Windows.Forms.NumericUpDown();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.appendPrefix = new System.Windows.Forms.CheckBox();
            this.label4 = new System.Windows.Forms.Label();
            this.targetFolder = new System.Windows.Forms.ComboBox();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.currentFile = new System.Windows.Forms.ToolStripStatusLabel();
            this.currentFileExtracted = new System.Windows.Forms.ToolStripStatusLabel();
            this.currentFilePercentage = new System.Windows.Forms.ToolStripStatusLabel();
            this.currentFileBw = new System.Windows.Forms.ToolStripStatusLabel();
            this.fileElapsed = new System.Windows.Forms.ToolStripStatusLabel();
            this.fileProgress = new System.Windows.Forms.ToolStripProgressBar();
            this.statusStrip2 = new System.Windows.Forms.StatusStrip();
            this.currentArchive = new System.Windows.Forms.ToolStripStatusLabel();
            this.currentVolume = new System.Windows.Forms.ToolStripStatusLabel();
            this.elapsed = new System.Windows.Forms.ToolStripStatusLabel();
            this.overallProgress = new System.Windows.Forms.ToolStripProgressBar();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.input.SuspendLayout();
            this.groupBox2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.archiveDepth)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.statusStrip1.SuspendLayout();
            this.statusStrip2.SuspendLayout();
            this.SuspendLayout();
            // 
            // cancelCommnad
            // 
            this.cancelCommnad.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.cancelCommnad.Enabled = false;
            this.cancelCommnad.Location = new System.Drawing.Point(406, 311);
            this.cancelCommnad.Name = "cancelCommnad";
            this.cancelCommnad.Size = new System.Drawing.Size(75, 23);
            this.cancelCommnad.TabIndex = 5;
            this.cancelCommnad.Text = "Cancel";
            this.cancelCommnad.UseVisualStyleBackColor = true;
            this.cancelCommnad.Click += new System.EventHandler(this.startCommand_Click);
            // 
            // pauseCommand
            // 
            this.pauseCommand.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.pauseCommand.Enabled = false;
            this.pauseCommand.Location = new System.Drawing.Point(484, 311);
            this.pauseCommand.Name = "pauseCommand";
            this.pauseCommand.Size = new System.Drawing.Size(75, 23);
            this.pauseCommand.TabIndex = 6;
            this.pauseCommand.Text = "Pause";
            this.pauseCommand.UseVisualStyleBackColor = true;
            // 
            // startCommand
            // 
            this.startCommand.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.startCommand.Enabled = false;
            this.startCommand.Location = new System.Drawing.Point(325, 311);
            this.startCommand.Name = "startCommand";
            this.startCommand.Size = new System.Drawing.Size(75, 23);
            this.startCommand.TabIndex = 0;
            this.startCommand.Text = "Start";
            this.startCommand.UseVisualStyleBackColor = true;
            this.startCommand.Click += new System.EventHandler(this.startCommand_Click);
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(6, 56);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(51, 13);
            this.label3.TabIndex = 6;
            this.label3.Text = "Archives:";
            // 
            // appendSourceName
            // 
            this.appendSourceName.AutoSize = true;
            this.appendSourceName.Checked = true;
            this.appendSourceName.CheckState = System.Windows.Forms.CheckState.Checked;
            this.appendSourceName.Location = new System.Drawing.Point(6, 17);
            this.appendSourceName.Name = "appendSourceName";
            this.appendSourceName.Size = new System.Drawing.Size(125, 17);
            this.appendSourceName.TabIndex = 5;
            this.appendSourceName.Text = "Last part from source";
            this.appendSourceName.UseVisualStyleBackColor = true;
            // 
            // targetBrowse
            // 
            this.targetBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.targetBrowse.Location = new System.Drawing.Point(475, 231);
            this.targetBrowse.Name = "targetBrowse";
            this.targetBrowse.Size = new System.Drawing.Size(75, 23);
            this.targetBrowse.TabIndex = 10;
            this.targetBrowse.Text = "Browse...";
            this.targetBrowse.UseVisualStyleBackColor = true;
            // 
            // archives
            // 
            this.archives.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.archives.CheckOnClick = true;
            this.archives.FormattingEnabled = true;
            this.archives.HorizontalScrollbar = true;
            this.archives.Location = new System.Drawing.Point(9, 73);
            this.archives.MinimumSize = new System.Drawing.Size(4, 24);
            this.archives.Name = "archives";
            this.archives.Size = new System.Drawing.Size(539, 109);
            this.archives.Sorted = true;
            this.archives.TabIndex = 7;
            // 
            // sourceFolderBrowse
            // 
            this.sourceFolderBrowse.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.sourceFolderBrowse.Location = new System.Drawing.Point(475, 29);
            this.sourceFolderBrowse.Name = "sourceFolderBrowse";
            this.sourceFolderBrowse.Size = new System.Drawing.Size(75, 23);
            this.sourceFolderBrowse.TabIndex = 3;
            this.sourceFolderBrowse.Text = "Browse...";
            this.sourceFolderBrowse.UseVisualStyleBackColor = true;
            this.sourceFolderBrowse.Click += new System.EventHandler(this.sourceFolderBrowse_Click);
            // 
            // sourceFolder
            // 
            this.sourceFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.sourceFolder.Location = new System.Drawing.Point(9, 32);
            this.sourceFolder.Name = "sourceFolder";
            this.sourceFolder.Size = new System.Drawing.Size(460, 20);
            this.sourceFolder.TabIndex = 2;
            this.toolTip1.SetToolTip(this.sourceFolder, "Folder from where archives should be collected from.");
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(6, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(44, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Source:";
            // 
            // input
            // 
            this.input.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.input.Controls.Add(this.archivesSelectionControl);
            this.input.Controls.Add(this.groupBox2);
            this.input.Controls.Add(this.archivesCount);
            this.input.Controls.Add(this.label6);
            this.input.Controls.Add(this.archiveDepth);
            this.input.Controls.Add(this.groupBox1);
            this.input.Controls.Add(this.label4);
            this.input.Controls.Add(this.label1);
            this.input.Controls.Add(this.sourceFolder);
            this.input.Controls.Add(this.targetBrowse);
            this.input.Controls.Add(this.targetFolder);
            this.input.Controls.Add(this.label3);
            this.input.Controls.Add(this.sourceFolderBrowse);
            this.input.Controls.Add(this.archives);
            this.input.Location = new System.Drawing.Point(3, 3);
            this.input.Name = "input";
            this.input.Size = new System.Drawing.Size(556, 302);
            this.input.TabIndex = 16;
            this.input.TabStop = false;
            this.input.Text = "Input";
            // 
            // archivesSelectionControl
            // 
            this.archivesSelectionControl.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.archivesSelectionControl.AutoSize = true;
            this.archivesSelectionControl.Location = new System.Drawing.Point(511, 55);
            this.archivesSelectionControl.Name = "archivesSelectionControl";
            this.archivesSelectionControl.Size = new System.Drawing.Size(37, 17);
            this.archivesSelectionControl.TabIndex = 19;
            this.archivesSelectionControl.Text = "All";
            this.archivesSelectionControl.ThreeState = true;
            this.archivesSelectionControl.UseVisualStyleBackColor = true;
            // 
            // groupBox2
            // 
            this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox2.Controls.Add(this.label2);
            this.groupBox2.Controls.Add(this.extraContent);
            this.groupBox2.Location = new System.Drawing.Point(262, 259);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(288, 38);
            this.groupBox2.TabIndex = 18;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Also include";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(6, 18);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(52, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "Wildcard:";
            // 
            // extraContent
            // 
            this.extraContent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.extraContent.Location = new System.Drawing.Point(61, 15);
            this.extraContent.Name = "extraContent";
            this.extraContent.Size = new System.Drawing.Size(221, 20);
            this.extraContent.TabIndex = 0;
            this.toolTip1.SetToolTip(this.extraContent, "Whitespace separated list of files to be copied to desitnation.");
            // 
            // archivesCount
            // 
            this.archivesCount.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.archivesCount.Location = new System.Drawing.Point(449, 56);
            this.archivesCount.Name = "archivesCount";
            this.archivesCount.Size = new System.Drawing.Size(56, 13);
            this.archivesCount.TabIndex = 15;
            this.archivesCount.Text = "0(0)";
            this.archivesCount.TextAlign = System.Drawing.ContentAlignment.TopRight;
            // 
            // label6
            // 
            this.label6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label6.AutoSize = true;
            this.label6.Location = new System.Drawing.Point(466, 11);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(39, 13);
            this.label6.TabIndex = 14;
            this.label6.Text = "Depth:";
            // 
            // archiveDepth
            // 
            this.archiveDepth.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.archiveDepth.Location = new System.Drawing.Point(511, 9);
            this.archiveDepth.Maximum = new decimal(new int[] {
            10,
            0,
            0,
            0});
            this.archiveDepth.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            -2147483648});
            this.archiveDepth.Name = "archiveDepth";
            this.archiveDepth.Size = new System.Drawing.Size(39, 20);
            this.archiveDepth.TabIndex = 13;
            this.toolTip1.SetToolTip(this.archiveDepth, "Selects the maximum number of subfolders to scan for archives.");
            this.archiveDepth.Value = new decimal(new int[] {
            2,
            0,
            0,
            0});
            // 
            // groupBox1
            // 
            this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.groupBox1.Controls.Add(this.appendSourceName);
            this.groupBox1.Controls.Add(this.appendPrefix);
            this.groupBox1.Location = new System.Drawing.Point(9, 259);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(244, 37);
            this.groupBox1.TabIndex = 12;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Append";
            // 
            // appendPrefix
            // 
            this.appendPrefix.AutoSize = true;
            this.appendPrefix.Location = new System.Drawing.Point(136, 17);
            this.appendPrefix.Name = "appendPrefix";
            this.appendPrefix.Size = new System.Drawing.Size(102, 17);
            this.appendPrefix.TabIndex = 11;
            this.appendPrefix.Text = "Prefix of archive";
            this.toolTip1.SetToolTip(this.appendPrefix, "The prefix is the folders  between the source folder and the archive itself.");
            this.appendPrefix.UseVisualStyleBackColor = true;
            // 
            // label4
            // 
            this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(6, 217);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(63, 13);
            this.label4.TabIndex = 8;
            this.label4.Text = "Destination:";
            // 
            // targetFolder
            // 
            this.targetFolder.AllowDrop = true;
            this.targetFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.targetFolder.FormattingEnabled = true;
            this.targetFolder.Location = new System.Drawing.Point(9, 233);
            this.targetFolder.Name = "targetFolder";
            this.targetFolder.Size = new System.Drawing.Size(460, 21);
            this.targetFolder.TabIndex = 9;
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.currentFile,
            this.currentFileExtracted,
            this.currentFilePercentage,
            this.currentFileBw,
            this.fileElapsed,
            this.fileProgress});
            this.statusStrip1.Location = new System.Drawing.Point(0, 364);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(565, 24);
            this.statusStrip1.TabIndex = 14;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // currentFile
            // 
            this.currentFile.Name = "currentFile";
            this.currentFile.Overflow = System.Windows.Forms.ToolStripItemOverflow.Never;
            this.currentFile.Size = new System.Drawing.Size(17, 19);
            this.currentFile.Text = "--";
            this.currentFile.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.currentFile.ToolTipText = "Text";
            // 
            // currentFileExtracted
            // 
            this.currentFileExtracted.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right;
            this.currentFileExtracted.Name = "currentFileExtracted";
            this.currentFileExtracted.Size = new System.Drawing.Size(21, 19);
            this.currentFileExtracted.Text = "--";
            // 
            // currentFilePercentage
            // 
            this.currentFilePercentage.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right;
            this.currentFilePercentage.Name = "currentFilePercentage";
            this.currentFilePercentage.Size = new System.Drawing.Size(21, 19);
            this.currentFilePercentage.Text = "--";
            // 
            // currentFileBw
            // 
            this.currentFileBw.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right;
            this.currentFileBw.Name = "currentFileBw";
            this.currentFileBw.Size = new System.Drawing.Size(21, 19);
            this.currentFileBw.Text = "--";
            // 
            // fileElapsed
            // 
            this.fileElapsed.Name = "fileElapsed";
            this.fileElapsed.Size = new System.Drawing.Size(470, 19);
            this.fileElapsed.Spring = true;
            this.fileElapsed.Text = "--:--:--";
            this.fileElapsed.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // fileProgress
            // 
            this.fileProgress.Enabled = false;
            this.fileProgress.Name = "fileProgress";
            this.fileProgress.Size = new System.Drawing.Size(100, 18);
            this.fileProgress.Visible = false;
            // 
            // statusStrip2
            // 
            this.statusStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.currentArchive,
            this.currentVolume,
            this.elapsed,
            this.overallProgress});
            this.statusStrip2.Location = new System.Drawing.Point(0, 340);
            this.statusStrip2.Name = "statusStrip2";
            this.statusStrip2.Size = new System.Drawing.Size(565, 24);
            this.statusStrip2.SizingGrip = false;
            this.statusStrip2.TabIndex = 18;
            this.statusStrip2.Text = "statusStrip2";
            // 
            // currentArchive
            // 
            this.currentArchive.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right;
            this.currentArchive.Name = "currentArchive";
            this.currentArchive.Size = new System.Drawing.Size(21, 19);
            this.currentArchive.Text = "--";
            this.currentArchive.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // currentVolume
            // 
            this.currentVolume.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right;
            this.currentVolume.Name = "currentVolume";
            this.currentVolume.Size = new System.Drawing.Size(21, 19);
            this.currentVolume.Text = "--";
            this.currentVolume.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // elapsed
            // 
            this.elapsed.Name = "elapsed";
            this.elapsed.Size = new System.Drawing.Size(508, 19);
            this.elapsed.Spring = true;
            this.elapsed.Text = "--:--:--";
            this.elapsed.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
            // 
            // overallProgress
            // 
            this.overallProgress.Name = "overallProgress";
            this.overallProgress.Size = new System.Drawing.Size(100, 18);
            this.overallProgress.Visible = false;
            // 
            // Unpacker
            // 
            this.AllowDrop = true;
            this.ClientSize = new System.Drawing.Size(565, 388);
            this.Controls.Add(this.statusStrip2);
            this.Controls.Add(this.input);
            this.Controls.Add(this.cancelCommnad);
            this.Controls.Add(this.pauseCommand);
            this.Controls.Add(this.startCommand);
            this.Controls.Add(this.statusStrip1);
            this.DoubleBuffered = true;
            this.MinimumSize = new System.Drawing.Size(240, 120);
            this.Name = "Unpacker";
            this.ShowInTaskbar = false;
            this.Text = "Unpacker";
            this.input.ResumeLayout(false);
            this.input.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.archiveDepth)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.statusStrip2.ResumeLayout(false);
            this.statusStrip2.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private void label5_Click(object sender, EventArgs e)
        {
            if (_collapsed)
            {
                base.Controls.Add(input);
                base.PerformLayout();
            }
            else
            {
                base.Controls.Remove(input);
            }
            _collapsed = !_collapsed;
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            if (_archives != null)
            {
                _archives.MaxDepth = (int)archiveDepth.Value;
            }
        }

        private void PerformStep()
        {
            overallProgress.PerformStep();
        }

        private void processTimer_Tick(object sender, EventArgs e)
        {
            UpdateElapsedTime();
        }

        private void SelectArchive(int i, bool b)
        {
            archives.SetSelected(i, true);
        }

        private void sourceFolder_Drop(DirectoryInfo dir)
        {
            _archives.Source = null;
            _archives.Source = dir;
        }

        private void sourceFolderBrowse_Click(object sender, EventArgs e)
        {
            BrowseSourceFolder();
        }

        private void startCommand_Click(object sender, EventArgs e)
        {
            if (_archives.Destination == null)
            {
                Logger.Log(string.Format("Error: {0}", "No destination defined!"));
            }
            else
            {
                var selected = new List<Archive>();
                foreach (var obj2 in archives.CheckedItems)
                {
                    selected.Add((Archive)obj2);
                }
                try
                {
                    _archives.AsyncProcess();
                }
                catch (Exception exception)
                {
                    Logger.Log(string.Format("Error: {0} - {1}", exception.Message, exception));
                }
            }
        }

        private void targetCreate_CheckedChanged(object sender, EventArgs e)
        {
            if (_archives != null)
            {
                _archives.AppendSourceName = appendSourceName.Checked;
            }
        }

        private void targetFolder_Drop(DirectoryInfo dir)
        {
            _archives.Destination = dir;
        }

        private void targetFolder_TextUpdate(object sender, EventArgs e)
        {
            string text = targetFolder.Text;
            try
            {
                _archives.Destination = new DirectoryInfo(text);
            }
            catch (Exception)
            {
                _archives.Destination = null;
            }
        }

        private void Unpacker_FormClosing(object sender, FormClosingEventArgs e)
        {
            _processCanceled = true;
            _archives.Stop();
            var destination = new string[targetFolder.Items.Count];
            targetFolder.Items.CopyTo(destination, 0);
            Settings.Default.Destinations.Clear();
            Settings.Default.Destinations.AddRange(destination);
            //Settings.Default.Destinations_SelectedIndex = targetFolder.SelectedIndex;
            //Settings.Default.ExtraContent = extraContent.Text;
            //Settings.Default.Append_Prefix = appendPrefix.Checked;
            //Settings.Default.Append_SourceName = appendSourceName.Checked;
            //Settings.Default.ArchiveDepth = (int)archiveDepth.Value;
            Settings.Default.Save();
        }

        private void Unpacker_Load(object sender, EventArgs e)
        {
        }

        private void unrar_ExtractionProgress(object sender, ExtractionProgressEventArgs e)
        {
            if (_processCanceled)
            {
                e.ContinueOperation = false;
            }
        }

        private void unrar_MissingVolume(object sender, MissingVolumeEventArgs e)
        {
            var dialog = new TextInputDialog();
            dialog.Value = e.VolumeName;
            dialog.Prompt = string.Format("Volume is missing.  Correct or cancel.", new object[0]);
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                e.VolumeName = dialog.Value;
                e.ContinueOperation = true;
            }
            else
            {
                e.ContinueOperation = false;
            }
        }

        private void unrar_NewFile(object sender, NewFileEventArgs e)
        {
            if (base.InvokeRequired)
            {
                base.Invoke(new NewFileDelegate(unrar_NewFile), new[] { sender, e });
            }
            else
            {
                if (e.FileInfo.FileName.Length > 15)
                {
                    currentFile.Text = e.FileInfo.FileName.Substring(0, 14) + "…";
                    toolTip1.SetToolTip(statusStrip1, e.FileInfo.FileName);
                }
                else
                {
                    currentFile.Text = e.FileInfo.FileName;
                    toolTip1.SetToolTip(statusStrip1, null);
                }
                fileProgress.Value = 0;
            }
        }

        private void unrar_NewVolume(object sender, NewVolumeEventArgs e)
        {
            if (base.InvokeRequired)
            {
                base.Invoke(new NewVolumeDelegate(unrar_NewVolume), new[] { sender, e });
            }
            else
            {
                currentVolume.Text = new FileInfo(e.VolumeName).Name;
            }
        }

        private void unrar_OutOfDiskSpace(object sender, OutOfDiskSpaceEventArgs e)
        {
            if (base.InvokeRequired)
            {
                base.Invoke(new OutOfDiskDelegate(unrar_OutOfDiskSpace), new[] { sender, e });
            }
            else if (
                MessageBox.Show(this,
                                "Disk is running low of storage space \n[" + PathUtils.FormatBytes(e.DestInfo.Free) +
                                " free]", "Unpack problem", MessageBoxButtons.RetryCancel,
                                MessageBoxIcon.Exclamation) == DialogResult.Cancel)
            {
                e.ContinueOperation = false;
            }
        }

        private void unrar_PasswordRequired(object sender, PasswordRequiredEventArgs e)
        {
            var dialog = new TextInputDialog();
            dialog.Prompt = string.Format("Password is required for extraction.", new object[0]);
            dialog.PasswordChar = '*';
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                e.Password = dialog.Value;
                e.ContinueOperation = true;
            }
            else
            {
                e.ContinueOperation = false;
            }
        }

        private void UpdateElapsedTime()
        {
            if ((_archives.Statistics != null) && (_archives.Statistics.Split != null))
            {
                fileElapsed.Text = _archives.Statistics.Split.TimeElapsed.ToString().Substring(0, 8);
                elapsed.Text = _archives.Statistics.TimeElapsed.ToString().Substring(0, 8);
                fileProgress.Value = (int)_archives.Statistics.Split.PercentCompleate;
                var percentCompleate = (int)_archives.Statistics.Split.PercentCompleate;
                currentFilePercentage.Text = percentCompleate + "%";
                currentFileBw.Text = PathUtils.FormatBytes(_archives.Statistics.Bandwidth) + "/s (Last " +
                                     PathUtils.FormatBytes(_archives.Statistics.Split.Bandwidth) + "/s)";
                currentFileExtracted.Text = PathUtils.FormatBytes(_archives.Statistics.Split.BytesExtracted) + " (" +
                                            PathUtils.FormatBytes(_archives.Statistics.Split.FileSize) + ")";
            }
        }

        // Properties

        // Nested Types

        #region Nested type: AddArchiveCallback

        private delegate void AddArchiveCallback(Archive item);

        #endregion

        #region Nested type: ClearArchivesCallback

        private delegate void ClearArchivesCallback();

        #endregion

        #region Nested type: NewFileDelegate

        private delegate void NewFileDelegate(object sender, NewFileEventArgs e);

        #endregion

        #region Nested type: NewVolumeDelegate

        private delegate void NewVolumeDelegate(object sender, NewVolumeEventArgs e);

        #endregion

        #region Nested type: OutOfDiskDelegate

        private delegate void OutOfDiskDelegate(object sender, OutOfDiskSpaceEventArgs e);

        #endregion

        #region Nested type: PerformStepDelegate

        private delegate void PerformStepDelegate();

        #endregion

        #region Nested type: ProcessEndedDelegate

        private delegate void ProcessEndedDelegate(ArchiveCollection sender);

        #endregion

        #region Nested type: ProcessNextArchiveDelegate

        private delegate void ProcessNextArchiveDelegate(object sender, Archive a);

        #endregion

        #region Nested type: ProcessStartedDelegate

        private delegate void ProcessStartedDelegate(ArchiveCollection sender);

        #endregion
    }
}